/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package wechat.rcv.util;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * RequestParser class
 *
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
public class XmlRequestParser {

	/**
	 * 提取出xml数据包中的加密消息
	 * 
	 * @param xmltext
	 *            待提取的xml字符串
	 * @return 提取出的加密消息字符串
	 * @throws AesException
	 */
	public static Object[] extract(String xmltext) {
		Object[] result = new Object[3];
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);

			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName("Encrypt");
			NodeList nodelist2 = root.getElementsByTagName("ToUserName");
			result[0] = 0;
			result[1] = nodelist1.item(0).getTextContent();
			result[2] = nodelist2.item(0).getTextContent();
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getMsgType(String xmltext) {
		return getElementByTag(xmltext,"MsgType");
	}
	public static Document getDocument(String xmltext){
		Document document = null;
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			document = db.parse(is);
		} catch (Exception e) {
			
		}
		return document;
	}
	public static String getElementByTag(String xmltext, String tagName) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);

			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName(tagName);
			return nodelist1.item(0).getTextContent();
		} catch (Exception e) {
			return null;
		}
	}
	public static String getElementByTagFromDoc(Document doc, String tagName) {
		try {
			Element root = doc.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName(tagName);
			return nodelist1.item(0).getTextContent();
		} catch (Exception e) {
			return null;
		}
	}
}
